package com.rocching.easychat.ui;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.QuickContactBadge;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.rocching.easychat.MainActivity;
import com.rocching.easychat.R;
import com.rocching.easychat.core.IApiCallback;
import com.rocching.easychat.core.UserIdentityContext;
import com.rocching.easychat.core.ViewClickListener;
import com.rocching.easychat.db.LocalUserService;
import com.rocching.easychat.model.UserModel;
import com.rocching.easychat.service.UserService;
import com.rocching.easychat.service.dto.LoginInput;
import com.rocching.easychat.util.AppUtil;
import com.rocching.easychat.util.HttpUtil;
import com.rocching.easychat.util.JsonUtil;
import com.rocching.easychat.util.StringUtil;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Call;

public class LoginActivity extends AppCompatActivity {
    private final String TAG = LoginActivity.class.getName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        Log.i(TAG, "login is started.");
        init();
    }

    private void init() {
        Button btnLogin = findViewById(R.id.btn_login);
        Button btnRegister = findViewById(R.id.btn_register);

        btnLogin.setOnClickListener(new ViewClickListener() {
            @Override
            public void onDClick(View v) {
                hideKeyboard(v.getWindowToken());

                EditText userName = findViewById(R.id.user_name);
                EditText userPwd = findViewById(R.id.user_pwd);

                login(userName.getText().toString(), userPwd.getText().toString());
            }
        });

        btnRegister.setVisibility(View.INVISIBLE);
        btnRegister.setOnClickListener(new ViewClickListener() {
            @Override
            public void onDClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
    }

    private void login(String account, String password) {
        if (StringUtil.isEmpty(account)) {
            showText(getString(R.string.user_name_tip2));
            return;
        }
        if (StringUtil.isEmpty(password)) {
            showText(getString(R.string.password_tip2));
            return;
        }

        LoginInput input = new LoginInput();
        input.setAccount(account);
        input.setPassword(password);

        UserService.getInstance().login(input, new IApiCallback<UserModel>() {
            @Override
            public void onResponse(boolean succeeded, String body, UserModel data) {
                if (succeeded) {
                    UserIdentityContext.set(data);
                    HttpUtil.setBearerValue(data.getToken());
                    writeDb(data);

                    goToHome();
                } else {
                    showText(getString(R.string.login_fail_tip));
                }
            }
        });
    }

    private void goToHome() {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
    }

    private void writeDb(UserModel model) {
        LocalUserService userService = LocalUserService.getInstance();
        userService.deleteAll();
        userService.insert(AppUtil.getTargetUserId(model.getId()), model);
    }

    private void showText(String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}